﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;

namespace SPWeather365.SPWeather365WebPart
{
    class SPWeather365EditorPart : EditorPart
    {
        Label lblAccountKey;
        TextBox txtAccountKey;
        Label lblSite;
        TextBox txtSite;
        LinkButton btnFindSite;
        Panel pnlSPWeather;
        Label lblMessage;

        /// <summary>
        /// Set the collapse title of the toolpart.
        /// </summary>
        public SPWeather365EditorPart()
        {
            Title = "SPWeather";         
        }

        /// <summary>
        /// Public properties for the WebPart to set any existing values.
        /// </summary>
        public string SiteName { get; set; }
        public string AccountKey {get;set;}

        protected override void RenderContents(HtmlTextWriter writer)
        {
            StringBuilder js = new StringBuilder();

            js.AppendLine("// IE: Edit the zone security settings and set Access data sources across domains to Enabled under Miscellaneous");            
            js.AppendLine("var user = '2a49275f-ad43-459d-abe1-6476685da1a2';");           
            js.AppendLine("var sites = new Array();");
            js.AppendLine("function findSite() {");
            js.AppendLine("var pwd = $('#" + txtAccountKey.ClientID + "').val();");
            js.AppendLine("$('#findSite').html('<img src=\"wait.gif\"/>');");
            js.AppendLine("var query = $('#" + txtSite.ClientID + "').val();");
            js.AppendLine("if (sites.length == 0) {");
            js.AppendLine("    $.support.cors = true;");
            js.AppendLine("    $.ajax({");
            js.AppendLine("        type: 'GET',");
            js.AppendLine("        beforeSend: function (xhr) {");
            js.AppendLine("            var bytes = Crypto.charenc.Binary.stringToBytes(user + ':' + pwd);");
            js.AppendLine("            var base64 = Crypto.util.bytesToBase64(bytes);");
            js.AppendLine("            xhr.setRequestHeader('Authorization', 'Basic ' + base64);");
            js.AppendLine("        },");
            js.AppendLine("        url: 'https://api.datamarket.azure.com/DataGovUK/MetOfficeWeatherOpenData/Site?$top=100000&$format=json',");
            js.AppendLine("        dataType: 'json',");
            js.AppendLine("        success: function (data) {");
            js.AppendLine("            $.each(eval(data).d.results, function (i, item) {");
            js.AppendLine("                sites[i] = item.Name;");
            js.AppendLine("                if (item.Name.toLowerCase().indexOf(query.toLowerCase()) > -1)");
            js.AppendLine("                    $('#" + txtSite.ClientID + "').val(item.Name);");
            js.AppendLine("            });");
            js.AppendLine("            $('#findSite').html('Find');");
            js.AppendLine("        },");
            js.AppendLine("        error: function (jqXHR, textStatus, errorThrown) {");
            js.AppendLine("            alert(errorThrown.message);");
            js.AppendLine("        }");
            js.AppendLine("    });");
            js.AppendLine("} else {");
            js.AppendLine("    $.each(sites, function (i, item) {");
            js.AppendLine("        if (item.toLowerCase().indexOf(query.toLowerCase()) > -1)");
            js.AppendLine("            $('#" + txtSite.ClientID + "').val(item);");
            js.AppendLine("    });");
            js.AppendLine("    $('#findSite').html('Find');");
            js.AppendLine("}");
            js.AppendLine("}");
            base.RenderContents(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "//crypto-js.googlecode.com/files/2.5.3-crypto-min.js");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();            

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine(js.ToString());
            writer.RenderEndTag();           
        }  

        /// <summary>
        /// Create and render the custom properties
        /// </summary>
        protected override void CreateChildControls()
        {
            Literal litJQuery = new Literal()
                {
                    Text = ""
                };

            Controls.Add(litJQuery);            
            pnlSPWeather = new Panel()
            {
                ID = "pnlSPWeather"
            };
            lblSite = new Label()
            {
                ID = "lblSite",
                Text = "Site:"
            };
            txtSite = new TextBox()
            {
                ID = "txtSite",
                Text = SiteName
            };
            lblAccountKey = new Label()
            {
                ID = "lblAccountKey",
                Text = "Account Key"                
            };
            txtAccountKey = new TextBox()
            {
                ID = "txtAccountKey",                
                ToolTip = "Azure data market Primary Account Key",
                Text = AccountKey
            };
            btnFindSite = new LinkButton()
            {
                ID = "btnFindSite",
                Text = "Find",
                OnClientClick="findSite(); return false;"
            };            
            lblMessage = new Label()
            {
                ID = "lblMessage"
            };

            Table table = new Table();
            table.Attributes.Add("Style", "width: 100%; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-collapse: collapse;");
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            Panel pnl = new Panel()
            {
                CssClass = "UserSectionHead"
            };
            pnl.Controls.Add(lblAccountKey);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserSectionBody"
            };
            Panel pnlUserControlGroup = new Panel()
            {
                CssClass = "UserControlGroup"
            };
            pnlUserControlGroup.Controls.Add(txtAccountKey);
            pnl.Controls.Add(pnlUserControlGroup);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserDottedLine"
            };
            cell.Controls.Add(pnl);
            row.Controls.Add(cell);
            table.Rows.Add(row);

            row = new TableRow();
            cell = new TableCell();
            pnl = new Panel()
            {
                CssClass = "UserSectionHead"
            };
            pnl.Controls.Add(lblSite);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserSectionBody"
            };
            pnlUserControlGroup = new Panel()
            {
                CssClass = "UserControlGroup"
            };
            pnlUserControlGroup.Controls.Add(txtSite);
            pnlUserControlGroup.Controls.Add(new Literal() { Text = "&nbsp;" });
            pnlUserControlGroup.Controls.Add(btnFindSite);
            pnlUserControlGroup.Controls.Add(new Literal() { Text = "<br/>" });
            pnlUserControlGroup.Controls.Add(lblMessage);
            pnl.Controls.Add(pnlUserControlGroup);
            cell.Controls.Add(pnl);
            row.Controls.Add(cell);
            table.Rows.Add(row);
           
            Controls.Add(table); 

            base.CreateChildControls();
        }

        private string jQueryCode()
        {
            StringBuilder script = new StringBuilder();
            script.AppendLine("$(document).ready(function(){");
            script.AppendLine(" alert('hello world!');");
            script.AppendLine("});");
            return script.ToString();
        }

        /// <summary>
        /// Update the propeties in the main web part with the settings.
        /// </summary>
        public override bool ApplyChanges()
        {                        
            SPWeather365WebPart wpSPWeather = (SPWeather365WebPart)WebPartToEdit;
            wpSPWeather.AccountKey = txtAccountKey.Text;
            wpSPWeather.SiteName = txtSite.Text;
            return true;
        }

        public override void SyncChanges()
        {
            SPWeather365WebPart wpSPWeather = (SPWeather365WebPart)WebPartToEdit;
            if(!string.IsNullOrEmpty(wpSPWeather.AccountKey))
                ((TextBox)this.FindControl("txtAccountKey")).Text = wpSPWeather.AccountKey;
            if (!string.IsNullOrEmpty(wpSPWeather.SiteName))
                ((TextBox)this.FindControl("txtSite")).Text = wpSPWeather.SiteName;
        }        
    }
}
